﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Celeriq.Utilities;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Celeriq.Service.Core
{
	public static class ServiceDomain
	{
		private static List<ServiceHost> _hosts = new List<ServiceHost>();
		private static Dictionary<string, string> _userList = new Dictionary<string, string>();

		public static int StartServices()
		{
			var configuration = ConfigurationSettings.GetInstance();

			var currentPath = ReflectionHelper.GetEntryAssemblyPath();
			var typeList = ReflectionHelper.GetCreatableObjectImplementsInterface(typeof(Celeriq.Utilities.IRepositoryService), currentPath);
			foreach (var t in typeList)
			{
				var service = ReflectionHelper.CreateInstance(t) as Celeriq.Utilities.IRepositoryService;
				var baseAddress = new Uri("net.tcp://localhost:1973/" + service.GetID().ToString());
				var host = new ServiceHost(service, baseAddress);
				_hosts.Add(host);

				var smb = new ServiceMetadataBehavior();
				smb.HttpGetEnabled = false;
				smb.MetadataExporter.PolicyVersion = PolicyVersion.Default;
				host.Description.Behaviors.Add(smb);

				host.Open();

				//Initialize the service
				var myBinding = new NetTcpBinding();
				myBinding.Security.Mode = SecurityMode.Transport;
				var myEndpoint = new EndpointAddress(host.BaseAddresses.First().AbsoluteUri);
				var client = new ChannelFactory<Celeriq.Utilities.IRepositoryService>(myBinding, myEndpoint);
				var repository = client.CreateChannel();
				var startUp = new Celeriq.Utilities.ServiceStartup() { RepositoryFolder = configuration.DataPath, CacheLength = 300 };
				var count = repository.StartUp(startUp);
			}
			return _hosts.Count;
		}

		public static void StopServices()
		{
			//Do Nothing
		}

	}
}
